package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRspVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.vo.LoginUserVo;
import com.atguigu.gulimall.auth.vo.RegUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendcode(@RequestParam("phone") String phone){
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis()-l<60000){
                return R.error(BizCodeEnum.VALID_AUTH_CODE_EXCEPTION.getCode(),BizCodeEnum.VALID_AUTH_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);

        //存入redis,60秒内不能再刷新
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone,code);
        return R.ok();
    }

    @PostMapping("/regUser")
    public String regUser(@Valid RegUserVo userVo, BindingResult result, RedirectAttributes redirectAttributes){

        if (result.hasErrors()){
            Map<String, String> error = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("error",error);
            /*
            * 此处不能使用请求转发，因为本身是post请求，请求转发是get 发生冲突
            * */
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //先校验验证码  进行用户注册
        String code = userVo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userVo.getPhone());
        if (!StringUtils.isEmpty(s)){
            if (!s.split("_")[0].equals(code)){
                Map<String, String> error=new HashMap<>();
                error.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("error",error);
                return "redirect:http://auth.gulimall.com/reg.html";
            }else {
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userVo.getPhone());
                //验证码通过 进行用户注册
                R regist = memberFeignService.regist(userVo);
                if (regist.getCode()==0){
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String, String> error=new HashMap<>();
                    error.put("msg",regist.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("error",error);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }
        }else {
            Map<String, String> error=new HashMap<>();
            error.put("code","验证码不存在");
            redirectAttributes.addFlashAttribute("error",error);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }

    @PostMapping("/login")
    public String login(LoginUserVo loginUserVo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(loginUserVo);
        if (login.getCode()==0){
            MemberRspVo data = login.getData("data", new TypeReference<MemberRspVo>() {
            });
            session.setAttribute("loginUser",data);
            return "redirect:http://gulimall.com";
        }else {
            Map<String, String> error=new HashMap<>();
            error.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("error",error);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
